"""
MSB watermark Scheme
"""
#
# msb.py
#
# Copyright (C) 2012 Robert Buj Gelonch
# Copyright (C) 2012 David Megias Jimenez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
__author__ = "Robert Buj Gelonch, and David Megias Jimenez"
__copyright__ = "Copyright 2012, Robert Buj Gelonch and David Megias Jimenez"
__credits__ = ["Robert Buj Gelonch", "David Megias Jimenez"]
__license__ = "GPL"
__version__ = "3"
__maintainer__ = "Robert Buj"
__email__ = "rbuj@uoc.edu"
__status__ = "Development"
__docformat__ = 'plaintext'

from itertools import cycle

from numpy import absolute
from numpy import array
from numpy import bitwise_and
from numpy import copysign
from numpy import fix
from numpy import int16
from numpy import log2
from numpy import ones
from numpy import sign
from uoc.wave.watermark.schemes.generic import generic_detection_function as D_generic

def embedding_function(S, w, P_watermarking_sheme):
    """
    embedding_function
    """
    # delete MSB
    msb = log2(P_watermarking_sheme['max_value'] + 1) - 1
    aux = absolute(array(S, dtype=int))
    sp = bitwise_and(aux, ((2 ** msb)-1).astype(int) * ones(len(S), dtype=int))
    # loop variables
    w_cycle_iterator = cycle(w)
    num_frames = int(fix(len(S) / P_watermarking_sheme['frame_size']))
    # loop: work within the splitted signal in blocks
    for frame in range(num_frames):
        start = frame * P_watermarking_sheme['frame_size']
        end = start + P_watermarking_sheme['frame_size']
        if w_cycle_iterator.next() == 1:
            sp[start:end] += 2 ** msb
    # last samples
    start = end
    if (num_frames * P_watermarking_sheme['frame_size']) != len(S):
        if w_cycle_iterator.next() == 1:
            sp[start:] += 2 ** msb
    s = copysign(sp, sign(S))
    return s.astype(int16)

def retrieval_function(s, P_watermarking_sheme):
    """
    Return the embedded watermark message within the watermarked
    audio signal
    """
    msb = log2(P_watermarking_sheme['max_value'] + 1) - 1
    return (absolute(s) >= (2 ** msb)).astype(int16)

def detection_function(s, w, P_watermarking_sheme):
    """
    Evaluate whether the watermarked signal contains the water-
    marked message
    """
    return D_generic(s, w, P_watermarking_sheme)